package com.lagou.controller;

import com.lagou.model.Response;
import com.lagou.model.UploadResult;
import com.lagou.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RequestMapping("/oss")
@RestController
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class.getName());

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file) {
        try {
            UploadResult uploadResult = fileService.upload(file);
            return new Response(uploadResult);
        } catch (IOException e) {
            LOGGER.error("上传文件失败", e);
        }

        return new Response(Response.BAD_REQUEST);
    }

    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse httpServletResponse) {
        try (ServletOutputStream outputStream = httpServletResponse.getOutputStream()) {
            fileService.download(fileName, outputStream);
        } catch (IOException e) {
            LOGGER.error("写出网络流失败", e);
        }
    }

    @RequestMapping("/delete")
    public Response delete(String fileName) {
        fileService.delete(fileName);
        return new Response();
    }
}
